package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.dto.PageResponse;
import com.example.foodwebbackend.entity.MerchantFood;
import com.example.foodwebbackend.service.MerchantFoodService;
import com.example.foodwebbackend.service.UserRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/foods")
@CrossOrigin(origins = "*")
public class PublicFoodController {

    @Autowired
    private MerchantFoodService merchantFoodService;
    
    @Autowired
    private UserRatingService userRatingService;

    /**
     * 分页获取菜品列表，支持分类筛选、搜索、排序
     */
    @GetMapping
    public ApiResponse<PageResponse<Map<String, Object>>> getFoods(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "12") Integer size,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String search,
            @RequestParam(defaultValue = "default") String sort) {
        try {
            // 计算偏移量
            int offset = (page - 1) * size;
            
            // 获取菜品列表
            List<MerchantFood> foods;
            int total;
            
            if (categoryId != null) {
                foods = merchantFoodService.getFoodsByCategory(categoryId, offset, size, search, sort);
                total = merchantFoodService.countFoodsByCategory(categoryId, search);
            } else {
                foods = merchantFoodService.getAllFoodsWithPagination(offset, size, search, sort);
                total = merchantFoodService.countAllFoods(search);
            }
            
            // 转换为前端需要的格式
            List<Map<String, Object>> result = new ArrayList<>();
            for (MerchantFood food : foods) {
                Map<String, Object> foodData = convertToFoodData(food);
                result.add(foodData);
            }
            
            // 构建分页响应
            PageResponse<Map<String, Object>> pageResponse = new PageResponse<>();
            pageResponse.setData(result);
            pageResponse.setPage(page);
            pageResponse.setSize(size);
            pageResponse.setTotal(total);
            pageResponse.setTotalPages((int) Math.ceil((double) total / size));
            
            return ApiResponse.success(pageResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error("获取菜品列表失败: " + e.getMessage());
        }
    }

    /**
     * 将MerchantFood转换为前端需要的数据格式
     */
    private Map<String, Object> convertToFoodData(MerchantFood food) {
        Map<String, Object> foodData = new HashMap<>();
        
        // 基本信息
        foodData.put("foodId", food.getFoodId());
        foodData.put("merchantId", food.getMerchantId());
        foodData.put("foodName", food.getFoodName());
        foodData.put("foodDescription", food.getFoodDescription());
        foodData.put("foodImagePath", food.getFoodImagePath() != null ? food.getFoodImagePath() : "/food.png");
        foodData.put("categoryId", food.getCategoryId());
        foodData.put("categoryName", food.getCategoryName());
        foodData.put("foodPrice", food.getPrice());
        foodData.put("merchantName", food.getMerchantName());
        foodData.put("createdTime", food.getCreatedTime());
        foodData.put("isActive", food.getIsActive());
        
        // 计算真实的评分和评论数
        try {
            List<Map<String, Object>> reviews = userRatingService.getFoodReviews(food.getFoodId());
            int reviewCount = reviews.size();
            double rating = 0.0;
            
            if (reviewCount > 0) {
                double sum = 0.0;
                for (Map<String, Object> review : reviews) {
                    Object ratingObj = review.get("rating");
                    if (ratingObj != null) {
                        if (ratingObj instanceof java.math.BigDecimal) {
                            sum += ((java.math.BigDecimal) ratingObj).doubleValue();
                        } else if (ratingObj instanceof Integer) {
                            sum += (Integer) ratingObj;
                        } else if (ratingObj instanceof Double) {
                            sum += (Double) ratingObj;
                        }
                    }
                }
                rating = sum / reviewCount;
                rating = Math.round(rating * 10.0) / 10.0; // 保留一位小数
            }
            
            foodData.put("rating", rating);
            foodData.put("reviewCount", reviewCount);
        } catch (Exception e) {
            // 如果获取评价失败，使用默认值
            foodData.put("rating", 0.0);
            foodData.put("reviewCount", 0);
        }
        
        return foodData;
    }
} 